package gormutil

import (
	"gorm.io/gorm"
	v1 "inspector/pkg/meta/v1"
)

// DefaultLimit define the default number of records to be retrieved.
const DefaultLimit = 1000
const DefaultPageSize = 10
const MaxPageSize = 100

// LimitAndOffset contains offset and limit fields.
type LimitAndOffset struct {
	Offset int
	Limit  int
}

// Unpointer fill LimitAndOffset with default values if offset/limit is nil
// or it will be filled with the passed value.
func Unpointer(offset *int64, limit *int64) *LimitAndOffset {
	var o, l int = 0, DefaultLimit

	if offset != nil {
		o = int(*offset)
	}

	if limit != nil {
		l = int(*limit)
	}

	return &LimitAndOffset{
		Offset: o,
		Limit:  l,
	}
}

// Paging contains pagination parameters
type Paging struct {
	Page     int
	PageSize int
}

// MakePaging creates a Paging object from request URL query
func MakePaging(p v1.PaginationOptions) Paging {

	page := 1
	if pg := p.Page; pg != nil {
		page = int(*pg)
	}
	pageSize := DefaultPageSize

	if pz := p.PageSize; pz != nil {
		pageSize = int(*pz)
	}

	if pageSize > MaxPageSize {
		pageSize = MaxPageSize
	} else if pageSize <= 0 {
		pageSize = DefaultPageSize
	}

	return Paging{
		Page:     page,
		PageSize: pageSize,
	}
}

// Paginate creates a paginate scope based on Paging object
func Paginate(p Paging) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		offset := (p.Page - 1) * p.PageSize
		return db.Offset(offset).Limit(p.PageSize)
	}
}
